package com.yingpai.fitness.dvp_2_0.main.activity.mine;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions2.Permission;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.ContextUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.util.DensityUtils;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.InfomationBean;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.yingpai.fitness.dvp_2_0.main.widget.DatePickerPopWin;
import com.yingpai.fitness.dvp_2_0.main.widget.RulerView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.functions.Consumer;

public class PersonalDetailActivity extends CommonActivity {

    @BindView(R.id.right_tv)
    TextView rightTv;
    @BindView(R.id.editUserImgIv)
    CircleImageView editUserImgIv;
    @BindView(R.id.userNameEt)
    EditText userNameEt;
    @BindView(R.id.userSexTv)
    TextView userSexTv;
    @BindView(R.id.userWeightTv)
    TextView userWeightTv;
    @BindView(R.id.UserHeightTv)
    TextView UserHeightTv;
    @BindView(R.id.userBustEt)
    EditText userBustEt;
    @BindView(R.id.userWaistEt)
    EditText userWaistEt;
    @BindView(R.id.userHipLineEt)
    EditText userHipLineEt;
    @BindView(R.id.userJobTv)
    EditText userJobTv;
    @BindView(R.id.userBirthTv)
    TextView userBirthTv;
    @BindView(R.id.bodyEt)
    EditText bodyEt;


    private String type;//身高还是体重

    private File file;
    private String currentDateStr;
    private Date mDate;
    private TokenBean tokenBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.personal_detail_activity);
    }

    @Override
    protected void initView() {
        setTitle("个人信息");
        rightTv.setText("提交");
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);
        mDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        currentDateStr = sdf.format(mDate);
    }

    @Override
    protected void initData() {
        showDialog(this, null);
        HttpParams params = new HttpParams();
        params.put("customerId", tokenBean.getId());
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_INFOMATION, params, Url.GET_INFOMATION, new Callback<InfomationBean>() {
            @Override
            public void onSuccess(InfomationBean infomationBean) {
                if (Constant.REQUEST_SUCCESS.equals(infomationBean.getResult())) {
                    userNameEt.setText(infomationBean.getMap().getCustomerInfo().getNickName() + "");
                    userSexTv.setText(infomationBean.getMap().getCustomerInfo().getSex() + "");
                    userWeightTv.setText(infomationBean.getMap().getCustomerInfo().getWeight() + "");
                    UserHeightTv.setText(infomationBean.getMap().getCustomerInfo().getHeight() + "");
                    userBustEt.setText(infomationBean.getMap().getCustomerInfo().getChestMeasurement() + "");
                    userWaistEt.setText(infomationBean.getMap().getCustomerInfo().getWaistline() + "");
                    userHipLineEt.setText(infomationBean.getMap().getCustomerInfo().getHipline() + "");
                    userJobTv.setText(infomationBean.getMap().getCustomerInfo().getProfession());
                    userBirthTv.setText(infomationBean.getMap().getCustomerInfo().getBirthday() == null ? "" : infomationBean.getMap().getCustomerInfo().getBirthday().substring(0, infomationBean.getMap().getCustomerInfo().getBirthday().indexOf(" ")));
                    bodyEt.setText(infomationBean.getMap().getCustomerInfo().getBodyShape());
                    Glide.with(PersonalDetailActivity.this)
                            .load(infomationBean.getMap().getCustomerInfo().getPhotoUrl())
                            .error(R.mipmap.icon_user_default)
                            .centerCrop()
                            .into(editUserImgIv);
                } else {
                    showToast(infomationBean.getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    private void showTakePhotoOrAlbumDialog() {
        TDialog tDialog = new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.take_photos_dialog_layout)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.BOTTOM)
                .addOnClickListener(R.id.tv_open_camera, R.id.tv_open_album, R.id.tv_cancel)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_open_camera:
//                                takePhoto();
                                FunctionConfig camera = new FunctionConfig.Builder()
                                        .setEnableEdit(true)
                                        .setEnableCrop(true)
                                        .setEnableRotate(true)
                                        .setCropSquare(true)
                                        .build();
                                //带配置
                                GalleryFinal.openCamera(300, camera, new GalleryFinal.OnHanlderResultCallback() {
                                    @Override
                                    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                                        if (reqeustCode == 300) {
                                            Glide.with(PersonalDetailActivity.this)
                                                    .load(resultList.get(0).getPhotoPath())
                                                    .into(editUserImgIv);
                                            file = new File(resultList.get(0).getPhotoPath());
                                        }
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {

                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.tv_open_album:
                                FunctionConfig album = new FunctionConfig.Builder()
                                        .setEnableEdit(true)
                                        .setEnableCrop(true)
                                        .setEnableRotate(true)
                                        .setCropSquare(true)
                                        .setEnablePreview(true)
                                        .build();
                                //带配置
                                GalleryFinal.openGallerySingle(200, album, new GalleryFinal.OnHanlderResultCallback() {
                                    @Override
                                    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                                        if (reqeustCode == 200) {
                                            Glide.with(PersonalDetailActivity.this)
                                                    .load(resultList.get(0).getPhotoPath())
                                                    .into(editUserImgIv);
                                            file = new File(resultList.get(0).getPhotoPath());
                                        }
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {

                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.tv_cancel:

                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();
    }


    /**
     * 选择性别
     */
    private void ChoiceSexDialog() {
        String sexStr[] = {"男", "女"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择性别");
        builder.setItems(sexStr, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (i == 0) {
                    userSexTv.setText("男");
                } else {
                    userSexTv.setText("女");
                }
            }
        });
        builder.create();
        builder.show();
    }

    /**
     * 选择生日Dialog
     */
    private void ChoiceBirthdayDialog() {
        DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(this, new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date choiceDate = null;
                try {
                    choiceDate = format.parse(dateDesc);
                    if (choiceDate.after(mDate)) {
                        Toast.makeText(PersonalDetailActivity.this, "所选日期不再范围内", Toast.LENGTH_SHORT).show();

                    } else {
                        userBirthTv.setText(dateDesc);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }).textConfirm("确定") //text of confirm button
                .textCancel("取消") //text of cancel button
                .btnTextSize(16) // button text size
                .viewTextSize(20) // pick view text size
                .colorCancel(Color.rgb(158, 155, 141)) //color of cancel button
                .colorConfirm(Color.rgb(217, 184, 120))//color of confirm button
                .minYear(1880) //min year in loop
                .maxYear(2550) // max year in loop
                .dateChose(currentDateStr) // date chose when init popwindow
                .build();
        pickerPopWin.showPopWin(this);
    }


    /**
     * 身高/体重选项弹出
     */
    private Dialog dialog;
    private TextView cancle, ok;
    private TextView tv_register_info_height_value, tv_register_info_weight_value;
    private LinearLayout heightLl, weightLl;
    private RulerView ruler_height;  //身高的view
    private RulerView ruler_weight;  //体重的view


    private void showHeOrWeDialog(final String type) {
        View view = View.inflate(this, R.layout.popwindow_bottom_layout,
                null);
        dialog = new Dialog(this, R.style.popwindowDialog);
        dialog.setContentView(view, new LinearLayout.LayoutParams(DensityUtils.getDisplayMetrics(ContextUtil.getContext()).widthPixels, LinearLayout.LayoutParams.WRAP_CONTENT));
        cancle = (TextView) view.findViewById(R.id.cancelTv);
        ok = (TextView) view.findViewById(R.id.okTv);

        heightLl = (LinearLayout) view.findViewById(R.id.heightLl);
        weightLl = (LinearLayout) view.findViewById(R.id.weightLl);
        if (type.equals("1")) {//身高
            heightLl.setVisibility(View.VISIBLE);
            weightLl.setVisibility(View.GONE);
            ruler_height = (RulerView) view.findViewById(R.id.ruler_height);
            tv_register_info_height_value = (TextView) view.findViewById(R.id.tv_register_info_height_value);
            ruler_height.setOnValueChangeListener(new RulerView.OnValueChangeListener() {
                @Override
                public void onValueChange(float value) {
                    tv_register_info_height_value.setText(value + "");
                }
            });
            ruler_height.setValue(165, 80, 250, 1);
        } else {//体重
            heightLl.setVisibility(View.GONE);
            weightLl.setVisibility(View.VISIBLE);
            ruler_weight = (RulerView) view.findViewById(R.id.ruler_weight);
            tv_register_info_weight_value = (TextView) view.findViewById(R.id.tv_register_info_weight_value);
            ruler_weight.setOnValueChangeListener(new RulerView.OnValueChangeListener() {
                @Override
                public void onValueChange(float value) {
                    tv_register_info_weight_value.setText(value + "");
                }
            });
            ruler_weight.setValue(55, 20, 200, 0.1f);
        }
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type.equals("1")) {
                    UserHeightTv.setText(tv_register_info_height_value.getText().toString());
                    dialog.cancel();
                } else {
                    userWeightTv.setText(tv_register_info_weight_value.getText().toString());
                    dialog.cancel();
                }
            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.x = 0;
        lp.y = 0;
        // 设置显示位置
        dialog.onWindowAttributesChanged(lp);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }


    @Override
    @OnClick({R.id.right_tv, R.id.userImgRl, R.id.userSexRl, R.id.userWeightRl, R.id.userHeightRl, R.id.userBirthRl})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.right_tv:
                if(!TextUtils.isEmpty(userNameEt.getText().toString().trim())){
                    showDialog(this, null);
                    HttpParams params = new HttpParams();
                    params.put("id", tokenBean.getId());
                    params.put("nickName", userNameEt.getText().toString().trim());
                    params.put("sex", userSexTv.getText().toString().trim());
                    params.put("weight", Float.parseFloat(userWeightTv.getText().toString().trim().equals("") ? 0 + "" : userWeightTv.getText().toString().trim()));
                    params.put("height", Float.parseFloat(UserHeightTv.getText().toString().trim().equals("") ? 0 + "" : UserHeightTv.getText().toString().trim()));
                    params.put("chestMeasurement", Float.parseFloat(userBustEt.getText().toString().trim().equals("") ? 0 + "" : userBustEt.getText().toString().trim()));
                    params.put("waistline", Float.parseFloat(userWaistEt.getText().toString().trim().equals("") ? 0 + "" : userWaistEt.getText().toString().trim()));
                    params.put("hipline", Float.parseFloat(userHipLineEt.getText().toString().trim().equals("") ? 0 + "" : userHipLineEt.getText().toString().trim()));
                    params.put("profession", userJobTv.getText().toString().trim());
                    params.put("birthday", userBirthTv.getText().toString().trim());
                    params.put("bodyShape", bodyEt.getText().toString().trim());
                    if (file == null) {
                        params.put("file", "");
                    } else {
                        params.put("file", file);
                    }
                    finalOkGo.request(RequestType.POSTFILE, Contacts.HOST_SERVER + Url.SAVE_INFOMATION, params, Url.SAVE_INFOMATION, new Callback<BaseResponse>() {
                        @Override
                        public void onSuccess(BaseResponse baseResponse) {
                            if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                EventBus.getDefault().post(Constant.UPDATA_INFOMATION);
                                finishActivity();
                            } else {
                                showToast(baseResponse.getMsg());
                            }
                            dismissDialog();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });
                }else{
                    showToast("请填写昵称");
                }
                break;
            case R.id.userImgRl:
                if (rxPermissions.isGranted(Manifest.permission.CAMERA) && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    showTakePhotoOrAlbumDialog();
                } else {
                    rxPermissions.requestEach(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Permission>() {
                                @Override
                                public void accept(Permission permission) throws Exception {
                                    if (permission.granted) {
                                        // 用户已经同意该权限
                                        showTakePhotoOrAlbumDialog();
                                    } else if (permission.shouldShowRequestPermissionRationale) {
                                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                        showToast("拒绝权限可能导致部分功能不能使用");
                                    } else {
                                        // 用户拒绝了该权限，并且选中『不再询问』
                                        showToast("拒绝权限可能导致部分功能不能使用，如果需要请在设置中修改");
                                    }
                                }
                            });
                }

                break;
            case R.id.userSexRl:
                ChoiceSexDialog();
                break;
            case R.id.userWeightRl:
                type = "2";
                showHeOrWeDialog(type);
                break;
            case R.id.userHeightRl:
                type = "1";
                showHeOrWeDialog(type);
                break;
            case R.id.userBirthRl:
                ChoiceBirthdayDialog();
                break;
        }
    }
}
